<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\model;
use think\facade\Db;
use think\facade\Session;
use think\facade\Cache;

/**
* 公众号
**/
class Wxopenapi
{
	static public function rebind($wid,$host){
		$confing = self::openConfing($wid);
		$pre_auth_code = self::getPreAuthCode($wid);
		$url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" . $confing["app_id"] . "&pre_auth_code=" . $pre_auth_code . "&redirect_uri=".$host."/wework/user/wechat/call?wid={$wid}"."&auth_type=1";
		return $url;
	}

	static public function openConfing($wid){
		$user = Db::table("kt_base_user")->where(["id"=>$wid])->find();
		$admin = Db::table("kt_base_agent")->where(["id"=>$user["agid"]])->find();
		$confing = Db::table("kt_open_platform_settings")->where(["uid"=>$admin["id"]])->find();
		if(!$confing){
			$admin = Db::table("kt_base_agent")->where(["isadmin"=>1])->find();
			$confing = Db::table("kt_open_platform_settings")->where(["uid"=>$admin["id"]])->find();
		}

        return $confing;
	}

	static public function getComponentAccessToken($wid="") {
		$wid = $wid ?: Session::get('wid');
		$confing = self::openConfing($wid);
		$cat = Db::table('kt_open_component_access_token')->where('app_id',$confing['app_id'])->find();
		if(isset($cat['component_access_token']) && intval(strtotime($cat['c_time'])) + 7000 > time()){
			//如果有未过期的ComponentAccessToken
		    return $cat['component_access_token'];
		}
		//没有或者过期了 重新请求
		$res = curlPost('https://api.weixin.qq.com/cgi-bin/component/api_component_token',json_encode([
				'component_appid'=>$confing['app_id'],
				'component_appsecret'=>$confing['app_secret'],
				'component_verify_ticket'=>$confing['component_verify_ticket']
			])
		);
		$res_arr = json_decode($res,1);
		if (array_key_exists('component_access_token', $res_arr)) {
			//请求component_access_token成功
			if(isset($cat['id'])) $data['id'] = $cat['id'];
			$data['app_id'] = $confing['app_id'];
			$data['component_access_token'] = $res_arr['component_access_token'];
			$data['c_time'] = date('Y-m-d H:i:s', time());
			Db::table('kt_open_component_access_token')->save($data);
			return $res_arr['component_access_token'];
		}else{
			return '';
		}
	}

	static public function getPreAuthCode($wid="") {
		$wid = $wid ?: Session::get('wid');
	  	$component_access_token = self::getComponentAccessToken($wid);
	  	if (!$component_access_token)return "";
		$confing = self::openConfing($wid);
		$body = curlPost("https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" . $component_access_token,
			json_encode([
			    "component_appid" => $confing["app_id"],
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr["pre_auth_code"];
	}

	/**
	 * 获取/刷新接口调用令牌，然后以该 token 调用公众号或小程序的相关 API
	 * 在公众号/小程序接口调用令牌（authorizer_access_token）失效时，可以使用刷新令牌
 	 */
	static public function getAuthorizerAccessToken($wid="",$authorizer_appid="",$auth_code=''){
		$wid = $wid ?: Session::get('wid');
		$confing = self::openConfing($wid);
		//参数是否存在
		if(!$auth_code){
			$auth = Db::table("kt_wework_authorizer_info")->where(["wid"=>$wid,"authorizer_appid"=>$authorizer_appid])->find();
			//不存在授权直接返回空
			if(!isset($auth['ctime'])) return '';
			//当前存储的令牌已经失效,发起令牌刷新请求
		    if (intval(strtotime($auth['ctime'])) + 7000 < time()) {
		    	$component_access_token = self::getComponentAccessToken($wid);
		    	if(!$component_access_token) return '';
			    $res = curlPost('https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$component_access_token,json_encode([
						'component_appid'=>$confing['app_id'],
						'authorizer_appid'=>$auth['authorizer_appid'],
						'authorizer_refresh_token'=>$auth['authorizer_refresh_token']
					])
				);
				$res_arr = json_decode($res,1);
				if (array_key_exists('authorizer_access_token', $res_arr)) {
					$data['id'] = $auth['id'];
					$data['authorizer_access_token'] = $res_arr['authorizer_access_token'];
					$data['authorizer_refresh_token'] = $res_arr['authorizer_refresh_token'];
					$data['ctime'] = date('Y-m-d H:i:s', time());
					Db::table('kt_wework_authorizer_info')->save($data);
					return $res_arr['authorizer_access_token'];
				}else{
					return '';
				}
		    }
		    //未失效
    		return $auth['authorizer_access_token'];
		}
		//auth_code获取令牌
		$component_access_token = self::getComponentAccessToken($wid);
		if(!$component_access_token) return '';
		$res = curlPost('https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token='.$component_access_token,
			json_encode([
				'component_appid'=>$confing['app_id'],
				'authorization_code'=>$auth_code
			])
		);
		$res_arr = json_decode($res,1);
		if (array_key_exists('authorization_info', $res_arr)) {
			$size = Db::table("kt_wework_authorizer_info")->where(["wid"=>$wid])->count();
			if(isset($auth['id'])) $data['id'] = $auth['id'];
			$data['wid'] = $wid;
			if(!$size)$data["type"] = 1;
			$data['authorizer_access_token'] = $res_arr['authorization_info']['authorizer_access_token'];//令牌
			$data['authorizer_refresh_token'] = $res_arr['authorization_info']['authorizer_refresh_token'];//刷新令牌
			$data['authorizer_appid'] = $res_arr['authorization_info']['authorizer_appid'];//授权方appid
			$data['ctime'] = date('Y-m-d H:i:s', time());
			$data["message"] = self::getAuthorizerInfo($res_arr['authorization_info']['authorizer_appid'],$wid);
			Db::table('kt_wework_authorizer_info')->save($data);
			return $res_arr['authorization_info']['authorizer_access_token'];
		}
		return '';
	}

	//获取当前用户的小程序基本信息
	static public function getAuthorizerInfo($authorizer_appid,$wid="") {
	  	$wid = $wid ?: Session::get('wid');
	  	$auth = Db::table("kt_wework_authorizer_info")->where(["wid"=>$wid,"authorizer_appid"=>$authorizer_appid])->find();
	  	$confing = self::openConfing($wid);
	  	$component_access_token = self::getComponentAccessToken($wid);//获取当前后台登陆着的用户的授权令牌
	  	$resp = curlPost(
	    	"https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=" . $component_access_token,
	    	json_encode([
	      		"component_appid"  => $confing["app_id"],
	      		"authorizer_appid" => $authorizer_appid,
	    	])
	  	);
	  	$resp_arr = json_decode($resp, 1);
	  	if (array_key_exists('authorizer_info', $resp_arr)) {
	    	//成功设置
	    	$message = json_encode($resp_arr);
	    	return $message;
	  	} 
    	return $resp_arr["errcode"];
	}
}